﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using blackhouse.Web.FasterFiles;
using System.Web.UI;
using blackhouse.JavaScript.JQuery;

namespace blackhouse.Web.Controls {
	public class DropDownListBox : ListBox {

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			JQueryLibraries jql = new JQueryLibraries();
			FasterFilesProvider files = new FasterFilesProvider();
			jql.IncludeJQueryUI();
			jql.IncludeFileBasedOnJQuery("blackhouse.Web.Controls.ui.dropdownchecklist-1.1-min.js,blackhouse.Web");

			ClientScriptManager jsManager = this.Page.ClientScript;
			string jsKey = "dropdowncheckbox" + this.ClientID;
			string jsScript = "<script language=\"javascript\" type=\"text/javascript\">$(document).ready(function(){$('#" + this.ClientID + "').dropdownchecklist({" + string.Join(",", this.getOptions()) + "});})</script>";
			if(!jsManager.IsClientScriptBlockRegistered(jsKey))
				jsManager.RegisterClientScriptBlock(typeof(DropDownListBox), jsKey, jsScript, false);
		}

		public override ListSelectionMode SelectionMode {
			get {
				return ListSelectionMode.Multiple;
			}
			set {
				base.SelectionMode = value;
			}
		}

		public override ListItemCollection Items {
			get {
				ListItemCollection items = base.Items;
				if(items.Count == 0) return items;
				if(items[0].Value != "all") {
					items.Insert(0, new ListItem("zaznacz wszystkie", "all"));
				}
				return items;
			}
		}

		public string[] getOptions() {
			List<string> options = new List<string>();
			if(!string.IsNullOrEmpty(this.Text))
				options.Add("emptyText: '" + this.Text + "'");
			if(!this.Width.IsEmpty && this.Width.Type == UnitType.Pixel)
				options.Add("width: " + this.Width.Value);
			if(!this.Height.IsEmpty && this.Height.Type == UnitType.Pixel)
				options.Add("maxDropHeight: " + this.Height.Value);
			options.Add("firstItemChecksAll: true");
			return options.ToArray();
		}

	}
}